from mqttdemo.mqtt1.mqttutil import MqttCallback, MqttUtil


class MyMqttCallback(MqttCallback):
    def on_connect(self, client, userdata, flags, rc):
        if rc == 0:
            print("Connected to MQTT Broker 111111111")
            client.subscribe("response/topic")  # 自动订阅
        else:
            print("Connection failed")

    def on_message(self, client, userdata, msg):
        print(f"Received: {msg.payload.decode()} on {msg.topic}")

# 使用示例
callback = MyMqttCallback()
mqtt_client = MqttUtil("localhost", callback=callback)
mqtt_client.connect()  # 连接后会自动触发 on_connect
mqtt_client.publish("test/topic", "Hello, MQTT!")
mqtt_client.loop_start()

try:
    while True:
        pass
except KeyboardInterrupt:
    mqtt_client.loop_stop()
    mqtt_client.disconnect()
